package com.mycirno.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.mycirno.dto.SearchResult;
import com.mycirno.service.DMZJService;

@Service
public class DMZJServiceImpl implements DMZJService {

	private Logger logger = Logger.getLogger(getClass());

	@Override
	public List<SearchResult> getSearchResult(String keyword, int page) {
		try {
			keyword = URLEncoder.encode(keyword, "utf-8");
			URL url = new URL("http://v2.api.dmzj.com/search/show/0/" + keyword + "/" + page + ".json");
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line = "";
			String html = "";
			while (null != (line = br.readLine())) {
				html += line;
			}
			br.close();
			List<SearchResult> searchResults = strToSearchResult(html);
			downLoad(searchResults.get(0).getCover());
			return searchResults;
		} catch (MalformedURLException e) {
			logger.error("URL错误");
		} catch (IOException e) {
			logger.equals("http IO错误");
		}
		return null;
	}
	
	public void show(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String keyword = URLEncoder.encode("一拳超人", "utf-8");
			String page = "0";
			URL url = new URL("http://v2.api.dmzj.com/search/show/0/" + keyword + "/" + page + ".json");
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line = "";
			String html = "";
			while (null != (line = br.readLine())) {
				html += line;
			}
			br.close();
			List<SearchResult> searchResults = strToSearchResult(html);
			resp.setContentType("text/html; charset=utf-8");
			PrintWriter pw = resp.getWriter();
			for (SearchResult searchResult : searchResults) {
				String image = searchResult.getCover();
				URL imageUrl = new URL(image);
				HttpURLConnection imageUrlConnection = (HttpURLConnection) imageUrl.openConnection();
				imageUrlConnection.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
				imageUrlConnection.setRequestProperty("Host", "images.dmzj.com");
				imageUrlConnection.setRequestProperty("Referer", "http://m.dmzj.com");
				pw.write("<br/><br/><img src='" + image + "' height='200' width='150'>");
			}
			pw.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public String imageToBase64 (String image) {
		String base64 = "";
		try {
			String[] arr = image.split("/");
			String name = arr[arr.length - 1];
			URL url = new URL(image);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
			urlConnection.setRequestProperty("Host", "images.dmzj.com");
			urlConnection.setRequestProperty("Referer", "http://m.dmzj.com");
			InputStream in = urlConnection.getInputStream();
			byte[] buffer = new byte[urlConnection.getContentLength()];
			in.read(buffer);
//			byte[] buffer = new byte[10 * 1024];
//			int bytes = 0;
//			FileOutputStream out = new FileOutputStream ("E:\\test\\" + name);
//			while (-1 != (bytes = in.read(buffer, 0, buffer.length))) {
//				out.write(buffer, 0, bytes);
//			}
			logger.info("长度：" + buffer.length);
//			out.close();
			in.close();
			base64 = new String(Base64.encodeBase64(buffer));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return base64;
	}
	
	public void downLoad (String image) {
		String path = "/image";
		try {
			URL url = new URL(image);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
			urlConnection.setRequestProperty("Host", "images.dmzj.com");
			urlConnection.setRequestProperty("Referer", "http://m.dmzj.com");
			File file = new File(path, "image.jpg");
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileOutputStream out = new FileOutputStream(file);
			InputStream in = urlConnection.getInputStream();
			byte[] buffer = new byte[1024];
			int length;
			while (-1 != (length = in.read(buffer))) {
				out.write(buffer, 0, length);
			}
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public List<SearchResult> strToSearchResult(String html) {
		JSONArray jsonArray = new JSONArray(html);
		List<SearchResult> searchResults = new ArrayList<SearchResult>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			logger.info(jsonObject.getString("cover"));
			SearchResult searchResult = new SearchResult(jsonObject.getLong("id"), jsonObject.getString("status"),
					jsonObject.getString("title"), jsonObject.getString("last_name"), imageToBase64(jsonObject.getString("cover")),
					jsonObject.getString("authors"), jsonObject.getLong("hot_hits"));
			searchResults.add(searchResult);
		}
		return searchResults;
	}

}
